/*
 *  Copyright (C) 2015 The yuhaiyang Android Source Project
 *
 *  Licensed under the yuhaiyang License, (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *       https://coding.net/yuhaiyang/License.git
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 *  @author: y.haiyang@qq.com
 *
 */

package com.yuhaiyang.xmlparser;

import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.List;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlSerializer;

import android.util.Xml;


public class PullBookParser implements IBookParser {

    @Override
    public List<Book> parse(InputStream input) throws Exception {
        List<Book> books = null;
        Book book = null;
        
        /**
         * 解析流程：
         *      1. 获取解析对象
         *      2. 设置属性
         *      3. 通过标签进行循环解析
         */
        // 初始化Pull解析对象
        XmlPullParser parser = Xml.newPullParser();
        parser.setInput(input, "UTF-8");
        // 获取第一个标签对象
        int eventType = parser.getEventType();

        /**
         * 流程:
         *   1. XmlPullParser.START_DOCUMENT    开始
         *   2. XmlPullParser.START_TAG         标签开始
         *   3. XmlPullParser.END_TAG           标签结束
         *   4. XmlPullParser.END_DOCUMENT      结束
         *
         *   流程1，4 只会走一次,  2 和 3 有几个标签 就会循环几次
         */
        while (eventType != XmlPullParser.END_DOCUMENT) {
            switch (eventType) {
                case XmlPullParser.START_DOCUMENT:
                    books = new ArrayList<Book>();
                    break;
                case XmlPullParser.START_TAG:
                    if (parser.getName().equals("book")) {
                        book = new Book();
                    } else if (parser.getName().equals("id")) {
                        eventType = parser.next();
                        book.setId(Integer.parseInt(parser.getText()));
                    } else if (parser.getName().equals("name")) {
                        eventType = parser.next();
                        book.setName(parser.getText());
                    } else if (parser.getName().equals("price")) {
                        eventType = parser.next();
                        book.setPrice(Float.parseFloat(parser.getText()));
                    }
                    break;
                case XmlPullParser.END_TAG:
                    if (parser.getName().equals("book")) {
                        books.add(book);
                        book = null;
                    }
                    break;
            }
            // 获取下一个标签
            eventType = parser.next();
        }
        return books;
    }

    @Override
    public String write(List<Book> books) throws Exception {
        /**
         * 写入流程：
         *     1. 获取写入对象
         *     2. 设置属性
         *     3. 循环写入
         */
        
        // 获取写入对象
        XmlSerializer serializer = Xml.newSerializer();
        
        // 添加Wirter和配置属性
        StringWriter writer = new StringWriter();
        //设置输出方向为writer
        serializer.setOutput(writer);
        
        // 开始写入标头
        serializer.startDocument("UTF-8", true);
        //serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
        
        changeLine(serializer);
        serializer.startTag("", "books");

        /**
         * 添加方法：
         *    1. startTag 设置tag
         *    2. text 设置 tag对应的内容
         *    3. endTag  结束tag
         */
        for (Book book : books) {
            changeLine(serializer);
            // 添加book比标签
            serializer.startTag("", "book");
            // 添加属性 例如：<book id="1003">
            //serializer.attribute("", "id", book.getId() + "");

            changeLine(serializer);
            serializer.startTag("", "name");
            serializer.text(book.getName());
            serializer.endTag("", "name");

            changeLine(serializer);
            serializer.startTag("", "id");
            serializer.text(String.valueOf(book.getId()));
            serializer.endTag("", "id");

            changeLine(serializer);
            serializer.startTag("", "price");
            serializer.text(String.valueOf(book.getPrice()));
            serializer.endTag("", "price");
            changeLine(serializer);

            serializer.endTag("", "book");
            changeLine(serializer);
        }
        serializer.endTag("", "books");
        serializer.endDocument();

        return writer.toString();
    }

    /**
     * 换行方法
     * @param serializer
     * @param enter
     */
    public static void changeLine(XmlSerializer serializer){
        String enter = System.getProperty("line.separator");
        try{
            serializer.text(enter);
        }catch(IOException e){
            System.out.println(e.getMessage());
        }
    }
}
